package org.desktop.web.server;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.desktop.web.client.user.UserService;
import org.desktop.web.server.util.RpcUtil;
import org.desktop.web.shared.domain.entities.SubProject;
import org.desktop.web.shared.domain.entities.User;
import org.json.JSONArray;
import org.json.JSONObject;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.sencha.gxt.data.shared.loader.PagingLoadConfig;
import com.sencha.gxt.data.shared.loader.PagingLoadResult;
import com.sencha.gxt.data.shared.loader.PagingLoadResultBean;

public class UserServiceImpl extends RemoteServiceServlet implements
		UserService {
	
	private Map<String,String> headers =new HashMap<String, String>();
	String userses = "http://127.0.0.1:8080/timesheet/userses";
	String usersprojects =  "http://127.0.0.1:8080/timesheet/usersprojects";

	@Override
	public PagingLoadResult<User> getUsers(Map<String,String> headers,PagingLoadConfig loadConfig) throws Exception{
		// TODO Auto-generated method stub
		try{
		String token = headers.get("token");
		URL _url = new URL(userses);
		HttpURLConnection con =RpcUtil.getUrlConnection(_url, "GET");
		con.setRequestProperty("Accept", "application/json");
		con.setRequestProperty("token", token);
		InputStream in = con.getInputStream();
		String result = IOUtils.toString(in);
		JSONArray users = new JSONArray(result);
		JSONArray usersResult = new JSONArray();
		for(int i=0;i<users.length();i++){
			JSONObject obj = users.getJSONObject(i);
			int id = obj.getInt("id");
			String descCustomer = obj.getJSONObject("idCustomer").getString("customerDesc");
			String descRole = obj.getJSONObject("idRole").getString("descRole");
			String login = obj.getString("login");
			JSONObject nobj = new JSONObject().put("id", id).put("customerDesc",descCustomer).put("descRole", descRole).put("login", login.toUpperCase());
			usersResult.put(nobj);
		}
		
		in.close();
//		result = new StringBuilder("{\"records\":").append(usersResult.toString()).append("}")
//				.toString();
		System.out.println("Payload: "+result);
		ObjectMapper map = new ObjectMapper();
		List<User> usersList = map.readValue(usersResult.toString(),new TypeReference<List<User>>() {
		});
		
//		AutoBeanFactory factory =AutoBeanFactorySource.create(UserAutoBeanFactory.class); 
//		AutoBean<UserRecordResult> usersList = AutoBeanCodex.decode(factory, UserRecordResult.class, result);
		PagingLoadResultBean<User> resultBean = new PagingLoadResultBean<User>(usersList,usersList.size(),30);
//		System.out.println("-------------");
//		System.out.println(usersList.as().getRecords());
//		System.out.println("-------------");
//		resultBean.setData(usersList.as().getRecords());
		System.out.println(resultBean.getData());
		return resultBean;
		}
		catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

//	@Override
//	public boolean addUserToProject(User user, Project project) throws Exception {
//		// TODO Auto-generated method stub
//
//		HttpURLConnection con = RpcUtil.getUrlConnection(new URL(usersprojects), "POST");
//		con.setRequestProperty("token", headers.get("token"));
//		con.setRequestProperty("Accept", "application/json");
//		
//		
//		return false;
//	}

	public void setHeaders(Map<String, String> headers) {
		this.headers = headers;
	}

	@Override
	public boolean hasSubProjects(List<SubProject> subprojects) throws Exception {
		// TODO Auto-generated method stub
		boolean result = false;
		for (Iterator iterator = subprojects.iterator(); iterator.hasNext();) {
			SubProject subProject = (SubProject) iterator.next();
			int id = subProject.getId();
			HttpURLConnection con = RpcUtil.getUrlConnection(new URL(usersprojects+"/subproject/"+id), "GET");
			RpcUtil.setToken(con, getThreadLocalRequest());
			InputStream in = con.getInputStream();
			int code = con.getResponseCode();
			in.close();
			result = code==302;
			if(result){
				break;
			}
		}
		return result;
	}

}
